package com.MediaVaultTest;

import java.io.IOException;
import java.util.logging.Logger;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.blobstore.ByteRange;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class Serve extends HttpServlet {
    private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
    private static final Logger log = Logger.getLogger(Serve.class.getName());
    
public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws IOException {

		QuotaLogic quotaLogic = new QuotaLogic();
		//MegaBytes
		long downloadSize = quotaLogic.getDownloadQuota();
		PersistenceManager pm = PMF.get().getPersistenceManager();
	
	    String stringKey = req.getParameter("key");
	    Key key = KeyFactory.stringToKey(stringKey);
	    
		//Get user currently logged in
		UserService userService = UserServiceFactory.getUserService();
	    User user = userService.getCurrentUser();
	    String userEmail = user.getEmail();
	    UserStore curuserStore = null;
		 Key userkey = KeyFactory.createKey(UserStore.class.getSimpleName(), userEmail);
		 try { 
			 curuserStore = pm.getObjectById(UserStore.class, userkey);
			 //See if anything is returned\
		 } catch (JDOObjectNotFoundException e) {
			 curuserStore = null;
		 }
	    
		//Get user the media file belongs to
	    
	    Format format = pm.getObjectById(Format.class, key);
	    Media media = format.getMedia();
	    UserStore userStore = media.getUserStore();
	    
	    
		//if same return media file
		if(userStore.equals(curuserStore)&&(downloadSize>(userStore.getmbDownload()+format.getSize()))){
			String rangeReq = req.getHeader("Content-Range");
			if(rangeReq==null){
				rangeReq = req.getHeader("Range");
			}
			if(rangeReq==null){  //if the header is not set, send everything
				userStore.setmbDownload(userStore.getmbDownload()+format.getSize());
				res.addHeader("Content-Disposition", "attachment; filename="+media.getTitle());
				blobstoreService.serve(format.getBlobKey(), res);
			} else {  //send only it
				String range[] = rangeReq.split("=", 2);
				range = range[1].split("-", 2);
				ByteRange byteRange;
				Long start = Long.parseLong(range[0].toString());
				Long end;
				if(range[1].toString()==""||range[1].toString()==null){
					end = start + 50000;
				} else {
					try{
						end = Long.parseLong(range[1].toString());
					} catch (NumberFormatException e) {
						end = start + 50000;
					}
				}
				if(end > format.getSize()){
					end = format.getSize();
				}
				byteRange = new ByteRange(start, end);
				userStore.setmbDownload(userStore.getmbDownload()+(end-start));
				blobstoreService.serve(format.getBlobKey(), byteRange, res);
			}
        	pm.close();
		} else {
        //else troll
			pm.close();
			if(downloadSize>(userStore.getmbDownload()+format.getSize())){
				res.sendRedirect("/");
			} else {
				res.sendRedirect("/");
			}
		}
    }
}